package com.yy.finvideoplayer

import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.net.ConnectivityManager
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import com.yy.finvideoplayer.media.IMediaCallback
import java.io.IOException

/**
 * @Description: Util
 * @Author: yiw89
 * @CreateDate: 2025/9/1 13:32
 * @Version: 1.0
 */
object Util {
    //单位毫秒
    fun stringForTime(timeMs: Int): String {
        if (timeMs <= 0) {
            return "00:00"
        }
        val totalSeconds = timeMs / 1000
        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    fun isWifiConnected(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI
    }

    //保持常亮
    fun keepScreenOn(context: Context) {
        scanForActivity(context).window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    //取消常亮
    fun keepScreenOff(context: Context) {
        scanForActivity(context).window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    //全屏
    fun setFullScreen(context: Context): Boolean {
        val w = scanForActivity(context).window
        val b = w.attributes.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN == WindowManager.LayoutParams.FLAG_FULLSCREEN
        w.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //w.addFlags(WindowManage.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        //hideBottomUIMenu(context)
        //showNavigationBar(context, false)
        return b
    }

    //取消全屏
    fun clearFullScreen(context: Context) {
        val w = scanForActivity(context).window
        w.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //w.clearFlags(WindowManage.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        //showBottomUIMenu(context)
        //showNavigationBar(context, true)
    }

    //横屏
    fun setLandscape(context: Context) {
        scanForActivity(context).requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

    //竖屏
    fun setPortrait(context: Context) {
        scanForActivity(context).requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

    //重力感应
    fun setSensor(context: Context) {
        scanForActivity(context).requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
    }

    /**
     * 返回当前屏幕是否为竖屏。
     */
    fun isScreenOrientationPortrait(context: Context): Boolean {
        val i = context.resources.configuration.orientation
        return i != Configuration.ORIENTATION_LANDSCAPE
    }

    /**
     * 隐藏虚拟按键
     */
    fun hideBottomUIMenu(context: Context) {
        showNavigationBar(context, false)
    }

    /**
     * 显示虚拟按键
     */
    fun showBottomUIMenu(context: Context) {
        showNavigationBar(context, true)
    }

    private fun showNavigationBar(context: Context, show: Boolean) {
        try {
            val a = scanForActivity(context)
            val w = a.window
            val v = w.decorView
            if (show) {
                if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
                    v.systemUiVisibility = View.GONE
                } else if (Build.VERSION.SDK_INT >= 19) {
                    v.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                }
            } else {
                if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
                    v.systemUiVisibility = View.VISIBLE
                } else if (Build.VERSION.SDK_INT >= 19) {
                    v.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or View.SYSTEM_UI_FLAG_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun dp2px(context: Context, value: Float): Int {
        val scale = context.resources.displayMetrics.densityDpi
        return (value * (scale / 160) + 0.5f).toInt()
    }

    fun scanForActivity(context: Context): Activity {
        if (context is Activity) {
            val a = context
            return a.parent ?: a
        } else if (context is ContextWrapper) {
            return scanForActivity(context.baseContext)
        }
        throw IllegalStateException("context得不到activity")
    }

    //url类型　0网络 -1本地 1直播流
    fun PaserUrl(url: String): Int {
        var mode = 0
        if (url.startsWith("file") || url.startsWith(ContentResolver.SCHEME_CONTENT) || url.startsWith(ContentResolver.SCHEME_ANDROID_RESOURCE))
            mode = -1
        if (url.endsWith("m3u8"))//...
            mode = 1
        return mode
    }

    /**
     * 实例化
     */
    fun <T> newInstance(className: String, iMediaCallback: IMediaCallback): T? {
        val paramsTypes = arrayOf<Class<*>>(IMediaCallback::class.java)
        try {
            val cls = Class.forName(className)
            val con = cls.getConstructor(*paramsTypes)
            return con.newInstance(iMediaCallback) as T
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 检查系统是否开启了自动旋转
     */
    fun isAutoRotationEnabled(context: Context): Boolean {
        return try {
            val result = Settings.System.getInt(
                context.contentResolver,
                Settings.System.ACCELEROMETER_ROTATION
            )
            result == 1
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
            false
        }
    }
}
